#!/usr/bin/env python
# -*- coding:utf-8 -*-

# import
import sys
import os
import socket
import re
import fcntl
import struct
import json
import time
import datetime
import threading
import hashlib
import base64
import glob
import urlparse
import urllib
import urllib2

# common
from common.log import log
from common.db.db import Db
from common.const import Const
from common.util import Util

# module

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)


class Stage:
    '''
    舞台管理
    '''

    def __init__(self):
        '''初始化'''
        log.debug('Stage init')

        # 系统变量获取
        env = os.environ
        self.local_address = '127.0.0.1'
        self.srs_http_port = '8102'
        try:
            self.srs_http_port = env['SRS_HTTP_PORT']
        except Exception, e:
            pass

        # 舞台分屏
        self.split = 1

        # 窗口内容
        self.subscreen = [-1] * 16

        # 加载数据库信息
        self.load_stage()

    def load_stage(self):
        '''加载舞台信息'''
        log.debug('load_stage')

        sql_ret = Db.execute('select SPLIT,SUBSCREEN from T_STAGE;')
        if len(sql_ret) > 0:
            self.split = int(sql_ret[0][0])
            if sql_ret[0][1] is not None:
                self.subscreen = [int(x) for x in sql_ret[0][1].split(',')]

    def query_stage(self):
        '''查询舞台信息'''
        log.debug('query_stage')

        ret_code = 1000
        ret_data = '{"split":%d,"subscreen":[%s]}' % (
            self.split, ','.join(str(x) for x in self.subscreen))

        return ret_code, ret_data

    def set_stage_split(self, split):
        '''设置舞台分屏'''
        log.debug(('set_stage_split, split:%d') % (split))

        ret_code = 1000
        ret_data = None

        if split != 0:
            self.split = split
            self.subscreen = [-1] * 16
            Db.execute('update T_STAGE set SPLIT=%d,SUBSCREEN="%s";' %
                       (self.split, ','.join(str(x) for x in self.subscreen)))

        return ret_code, ret_data

    def set_stage_subscreen(self, pos, device_id):
        '''设置舞台窗口内容'''
        log.debug(('set_stage_subscreen, pos:%d, device_id:%d') %
                  (pos, device_id))

        ret_code = 1000
        ret_data = None

        if pos != -1:
            self.subscreen[pos] = device_id
            Db.execute('update T_STAGE set SUBSCREEN="%s";' %
                       (','.join(str(x) for x in self.subscreen)))

        return ret_code, ret_data

    def get_device_id_by_pos(self, pos):
        '''查询指定位置上的设备ID'''
        log.debug(('get_device_id_by_pos, pos:%d') % (pos))

        if pos < len(self.subscreen):
            return self.subscreen[pos]

        return -1
